package com.zyzo.demo.appengine.server;

import java.util.ArrayList;
import java.util.List;

import org.restlet.resource.ServerResource;

import com.zyzo.demo.appengine.model.Item;
import com.zyzo.demo.appengine.model.ItemDao;
import com.zyzo.demo.appengine.model.ServerReponse;

public class ItemController extends ServerResource implements ItemControllerInterface {

	@Override
	public ServerReponse create(Item o) 
	{
		try {
			ItemDao.getInstance().createItem( o  );
		} catch (Exception e) {
			return new ServerReponse( ServerReponse.STATUS_ERR , e.getMessage() );
		}
		return new ServerReponse( ServerReponse.STATUS_OK , "ok" );
		
	}

	@Override
	public ServerReponse update(Item o) 
	{
		try {
			ItemDao.getInstance().updateItem( o );
		} catch (Exception e) {
			return new ServerReponse( ServerReponse.STATUS_ERR , e.getMessage() );
		}
		return new ServerReponse( ServerReponse.STATUS_OK , "ok" );
		
	}

	@Override
	public List<Item> getItem() 
	{
		/*
		 * Recuperation d'args ?
		 */
		String itemid = (String) getRequest().getAttributes().get("id");
		if( itemid != null )
		{
			ArrayList<Item> l = new ArrayList<Item>(1);
			long litemid = 0;
			try
			{
				litemid = Long.parseLong(itemid );
			}
			catch(Exception e){}
			
			if( litemid > 0 )
			{
				Item u =  ItemDao.getInstance().getItem( litemid );
				if( u != null )
				{
					l.add(u);
				}
			}
			return l;
		}
		else
			return  ItemDao.getInstance().getAllItem();

	}

}
